import numpy as np
import matplotlib.pyplot as plt
import os
import caffe
import sys
import pickle
#import cv2

caffe_root = ''

deployPrototxt ='E:/Projects/caffe/windows/caffe-windows/caffe/models/bvlc_reference_caffenet/deploy.prototxt'
modelFile = 'E:/Projects/caffe/windows/caffe-windows/logs/caffenet/caffenet_train_iter_100000.caffemodel'
meanFile = 'D:/caffetrain1/mean.npy'
#imageListFile = '/home/chenjie/DataSet/CompCars/data/train_test_split/classification/test_model431_label_start0.txt'
#imageBasePath = '/home/chenjie/DataSet/CompCars/data/cropped_image'
#resultFile = 'PredictResult.txt'

#网络初始化
def initilize():
    print ('initilize ... ')
    sys.path.insert(0,'E:/Projects/caffe/windows/caffe-windows/caffe_python_matlab/caffe/' + 'python')
    caffe.set_mode_gpu()
    caffe.set_device(0)
    net = caffe.Net(caffe_root + deployPrototxt, caffe_root + modelFile,caffe.TEST)
    return net

#取出网络中的params和net.blobs的中的数据
def getNetDetails(image, net):
    # input preprocessing: 'data' is the name of the input blob == net.inputs[0]
    transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
    transformer.set_transpose('data', (2,0,1))
    transformer.set_mean('data', np.load(caffe_root + meanFile).mean(1).mean(1)) # mean pixel
    transformer.set_raw_scale('data', 255)  
    # the reference model operates on images in [0,255] range instead of [0,1]
    #transformer.set_channel_swap('data', (2,1,0))  
    # the reference model has channels in BGR order instead of RGB
    # set net to batch size of 50
    net.blobs['data'].reshape(1,1,200,200)

    net.blobs['data'].data[0] = transformer.preprocess('data', caffe.io.load_image(image,False))
    out = net.forward()
    
    #网络提取conv1的卷积核
    filters = net.params['conv1'][0].data
    with open('FirstLayerFilter.pickle','wb') as f:
        pickle.dump(filters,f)
    vis_square(filters.transpose(0, 2, 3, 1))
     #conv1的特征图
    feat = net.blobs['conv1'].data[0, :32]
    with open('FirstLayerOutput.pickle','wb') as f:
       pickle.dump(feat,f)
    vis_square(feat,padval=1)
    pool = net.blobs['pool1'].data[0,:32]
    with open('pool1.pickle','wb') as f:
        pickle.dump(pool,f)
    vis_square(pool,padval=1)
    filters1 = net.params['conv2'][0].data
    vis_square(filters1.reshape(16*64,3,3)[:64])
    feat = net.blobs['conv2'].data[0, :64]
    vis_square(feat,padval=1)
    pool = net.blobs['pool2'].data[0,:64]
    vis_square(pool,padval=1)
    filters = net.params['conv3'][0].data
    vis_square(filters.reshape(64*96,3,3)[:96])
    feat = net.blobs['conv3'].data[0, :96]
    vis_square(feat,padval=1)
    filters = net.params['conv4'][0].data
    vis_square(filters.reshape(48*128,3,3)[:128])
    feat = net.blobs['conv4'].data[0, :128]
    vis_square(feat,padval=1)
    filters = net.params['conv5'][0].data
    vis_square(filters.reshape(64*128,3,3)[:128])
    feat = net.blobs['conv5'].data[0, :128]
    vis_square(feat,padval=1)
    pool = net.blobs['pool5'].data[0,:128]
    vis_square(pool,padval=1)
    feat = net.blobs['fc6'].data[0]  
    plt.subplot(2, 1, 1)  
    plt.plot(feat.flat)  
    plt.subplot(2, 1, 2)  
    _ = plt.hist(feat.flat[feat.flat > 0], bins=100)  
    plt.show() 
    feat = net.blobs['fc7'].data[0]  
    plt.subplot(2, 1, 1)  
    plt.plot(feat.flat)  
    plt.subplot(2, 1, 2)  
    _ = plt.hist(feat.flat[feat.flat > 0], bins=100)  
    plt.show() 
    feat = net.blobs['fc8'].data[0]  
    plt.subplot(2, 1, 1)  
    plt.plot(feat.flat)  
    plt.subplot(2, 1, 2)  
    _ = plt.hist(feat.flat[feat.flat > 0], bins=100)  
    plt.show() 


# 此处将卷积图和进行显示，
def vis_square(data, padsize=1, padval=0 ):
    data -= data.min()
    data /= data.max()
    
    #让合成图为方
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 1)
    data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
    #合并卷积图到一个图像中
    
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 1) + tuple(range(4, data.ndim + 3)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    print (data.shape)
    plt.imshow(data)
    plt.show()

if __name__ == "__main__":
    net = initilize()
    testimage = 'C:/Users/liwenjun/Desktop/normal_1276.png'
    getNetDetails(testimage, net)